#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
截图服务
提供截图功能
"""

import os
from pathlib import Path
from typing import Optional

from app.core.config import settings


class ScreenshotService:
    """截图服务"""
    
    def __init__(self):
        self.screenshot_path = os.path.abspath(settings.SCREENSHOT_PATH)
        Path(self.screenshot_path).mkdir(parents=True, exist_ok=True)
        
    async def create_screenshot(self, stream_id: str, output_path: str = None) -> str:
        """创建截图"""
        if not output_path:
            output_path = self.get_screenshot_path(stream_id)
            
        # 确保输出目录存在
        Path(os.path.dirname(output_path)).mkdir(parents=True, exist_ok=True)
        
        # 构建截图命令
        command = [
            "ffmpeg",
            "-i", f"rtmp://localhost:1935/live/{stream_id}",
            "-vframes", "1",
            "-y",
            output_path
        ]
        
        # 执行命令
        import subprocess
        result = subprocess.run(command, capture_output=True, text=True)
        
        if result.returncode != 0:
            raise Exception(f"截图失败: {result.stderr}")
            
        return output_path
        
    def get_screenshot_path(self, stream_id: str) -> str:
        """获取截图路径"""
        filename = f"{stream_id}_{int(os.time())}.jpg"
        return os.path.join(self.screenshot_path, filename)


# ScreenshotService单例实例
_screenshot_service_instance = None


def get_screenshot_service():
    """获取ScreenshotService单例实例"""
    global _screenshot_service_instance
    if _screenshot_service_instance is None:
        _screenshot_service_instance = ScreenshotService()
    return _screenshot_service_instance